import logging
from rich.logging import RichHandler
from logging.handlers import RotatingFileHandler

# CRITICAL = 50
# ERROR    = 40
# WARNING  = 30
# INFO     = 20
# DEBUG    = 10  # 调试信息，通常用于开发阶段，包含函数调用、变量值等
VERBOSE = 9  # 详细的调试信息，通常用于开发阶段，包含函数调用、变量值等
TRACE = 5  # 追踪程序执行的每一步，函数的每次进入和返回，复杂流程中的中间状态
SPAM = 3  # 极度频繁的、极低价值的调试信息，默认关闭，只有在需要深入追踪细节时才开启


class CustomLogger(logging.getLoggerClass()):
    def verbose(self, msg, *args, **kwargs):
        if self.isEnabledFor(VERBOSE):
            self._log(VERBOSE, msg, args, **kwargs)

    def trace(self, msg, *args, **kwargs):
        if self.isEnabledFor(TRACE):
            self._log(TRACE, msg, args, **kwargs)

    def spam(self, msg, *args, **kwargs):
        if self.isEnabledFor(SPAM):
            self._log(SPAM, msg, args, **kwargs)


class Logger:
    def __init__(self, log_level):
        self.level = logging.INFO
        self.log_level = log_level
        self.__parse_args()
        self.__log_init()

    def __log_init(self):
        logging.addLevelName(VERBOSE, "VERBOSE")
        logging.addLevelName(TRACE, "TRACE")
        logging.addLevelName(SPAM, "SPAM")
        logging.setLoggerClass(CustomLogger)

        formatter = logging.Formatter(
            "%(asctime)s %(levelname)-8s %(name)-8s %(message)s"
        )

        console_handler = RichHandler()
        console_handler.setLevel(level=self.level)
        console_handler.setFormatter(formatter)

        log_file = "logs/service.log"
        log_file_size = 8 * 1024 * 1024
        log_file_count = 128
        file_handler = RotatingFileHandler(
            log_file, maxBytes=log_file_size, backupCount=log_file_count
        )
        file_handler.setLevel(SPAM)
        file_handler.setFormatter(formatter)

        root_logger = logging.getLogger()
        root_logger.handlers.clear()
        root_logger.setLevel(SPAM)
        root_logger.addHandler(console_handler)
        root_logger.addHandler(file_handler)

    def __parse_args(self):
        if self.log_level == "spam":
            self.level = SPAM
        elif self.log_level == "trace":
            self.level = TRACE
        elif self.log_level == "verbose":
            self.level = VERBOSE
        elif self.log_level == "debug":
            self.level = logging.DEBUG
        elif self.log_level == "info":
            self.level = logging.INFO
        elif self.log_level == "warning":
            self.level = logging.WARNING
        elif self.log_level == "error":
            self.level = logging.ERROR
        else:
            self.level = logging.INFO
